package com.hnichr.ump;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.hnichr.ump.common.ping.vo.SendResultVo;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.*;

public class SmsThread implements Runnable{
    private static final String APP_KEY = "vFj23Pdl";
    private static final String APP_SECRET = "391ae60cc614bd9ff1d296adfb8a58395fd5c7ad";

    private static final String URL = "https://ping.hn-talent.com/send/v1/sendSms";

    private static final Logger logger = LoggerFactory.getLogger(SmsThread.class);
    @Override
    public void run() {
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("appKey",APP_KEY);
        treeMap.put("mobiles","18637109325");
        treeMap.put("smsContent","尊敬的加菲猫，您已成功预约人才绿通机场/高铁服务，预约时间为：2024-02-01 10:00，稍后会有工作人员与您联系提供专属服务，感谢您对河南省人才工作的支持（咨询热线：0371-66666666）！");
        treeMap.put("timestamp",String.valueOf(new Date().getTime()));
        treeMap.put("nonce", IdUtil.simpleUUID());
        treeMap.put("signatureMethod","HMAC-SHA1");
        String signature = getSignature(treeMap);
        treeMap.put("signature",signature);
        try{
            HttpResponse response = HttpUtil.createPost(URL).contentType("application/json").body(JSON.toJSONString(treeMap)).execute();
            String responseBody = response.body();
            SendResultVo sendResultVo = JSON.parseObject(responseBody,SendResultVo.class);
            System.out.println(">>>>>>>>>>>responseBody:"+Thread.currentThread().getId()+":"+responseBody);
        }
        catch (Exception e){
            logger.error(">>>>>>>>>>>短信发送异常",e);
        }
    }

    public String getSignature(SortedMap<String,String> treeMap){
        List<String> valuesList = new ArrayList<>();
        for(Map.Entry<String,String> entry:treeMap.entrySet()){
            valuesList.add(entry.getValue());
        }
        String values = String.join("&",valuesList);
        try{
            String encodedValues = URLEncoder.encode(values,"UTF-8");
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec spec = new SecretKeySpec(APP_SECRET.getBytes(), "HmacSHA1");
            mac.init(spec);
            byte[] byteHMAC = mac.doFinal(encodedValues.getBytes());
            org.apache.commons.codec.binary.Base64 base64 = new Base64();
            return base64.encodeAsString(byteHMAC);
        }
        catch (Exception e){
            return null;
        }
    }
}
